package reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test6 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        Class c = Class.forName("reflection.User");
        Constructor constructor = c.getDeclaredConstructor(String.class, int.class);
        User user = (User) constructor.newInstance("张鑫", 12);
        System.out.println(user);

        //通过反射操作方法
        User user2= (User) c.getConstructor().newInstance();
        Method setName = c.getDeclaredMethod("setName", String.class);
        setName.invoke(user2,"张鑫2");
        System.out.println(user2.getName());


        //通过反射操作属性
        User user3= (User) c.getConstructor().newInstance();
        Field name = c.getDeclaredField("name");
        //不能直接操作私有属性，需要关闭程序的安全监测
        name.setAccessible(true);
        name.set(user3,"张鑫3");
        System.out.println(user3.getName());
    }
}
